package com.candoo.oil.scan;

import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.content.SharedPreferences;

import java.io.File;
import java.io.FileWriter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.StringTokenizer;

import com.magicrf.uhfreaderlib.reader.Tools;
import com.magicrf.uhfreaderlib.reader.UhfReader;

public class ScanActivity extends AppCompatActivity {

    private String _id="";
    private int _count=0;
    private ProgressBar _pb;

    private ListView listViewData;
    private ArrayList<P_EPC> listEPC;
    private ArrayList<Map<String, Object>> listMap;
    private boolean runFlag = true;
    private boolean startFlag = false;
    private boolean fullFlag = false;
    private String serialPortPath = "/dev/ttyS2";
    private UhfReader reader ; //超高频读写器
    private UhfReaderDevice readerDevice; // 读写器设备，抓哟操作读写器电源

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_scan);
        initView();
        Intent intent = getIntent();
        _id = intent.getStringExtra("item_id");
        _count = intent.getIntExtra("item_count",0);
        _pb=((ProgressBar) findViewById(R.id.pb_Count));
        _pb.setMax(_count);
        _pb.setProgress(0);
        //_pb.setSecondaryProgress(60);

        ((TextView) findViewById(R.id.scan_name)).setText(intent.getStringExtra("item_name"));
        ((TextView) findViewById(R.id.scan_count)).setText("总数量:"+_count);

//获取读写器实例，若返回Null,则串口初始化失败
        SharedPreferences sharedPortPath = getSharedPreferences("portPath", 0);
        serialPortPath =  sharedPortPath.getString("portPath", "/dev/ttyS2");
        UhfReader.setPortPath(serialPortPath);
        reader = UhfReader.getInstance();
        //获取读写器设备示例，若返回null，则设备电源打开失败
        readerDevice = UhfReaderDevice.getInstance();
        if(reader == null){
            Log.e("Scan","serialport init fail");
            //textVersion.setText("serialport init fail");
            //setButtonClickable(buttonClear, false);
           // setButtonClickable(buttonStart, false);
            //setButtonClickable(buttonConnect, false);
            return ;
        }
        if (readerDevice == null)
        {
            Log.e("Scan","UHF reader power on failed");
          //  textVersion.setText("UHF reader power on failed");
//			setButtonClickable(buttonClear, false);
//			setButtonClickable(buttonStart, false);
//			setButtonClickable(buttonConnect, false);
//			return ;
        }
        try {
            Thread.sleep(100);
        } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        //获取用户设置功率,并设置
        SharedPreferences shared = getSharedPreferences("power", 0);
        int value = shared.getInt("value", 26);

        value=Config.PowerValue;
        Log.e("sane", "value" + value);
        reader.setOutputPower(value);

        Thread thread = new InventoryThread();
        thread.start();

        _run();
        /*
        ListView list = (ListView) findViewById(R.id.lv_scanlist);
        ArrayList<HashMap<String, String>> mylist = new ArrayList<HashMap<String, String>>();
        for(int i=0;i<30;i++)
        {
            HashMap<String, String> map = new HashMap<String, String>();
            map.put("ItemTitle", "This is Title.....");
            map.put("ItemText", "This is text.....");
            mylist.add(map);
        }
        //生成适配器，数组===》ListItem
        SimpleAdapter mSchedule = new SimpleAdapter(this, //没什么解释
                mylist,//数据来源
                R.layout.listitem_detail,//ListItem的XML实现

                //动态数组与ListItem对应的子项
                new String[] {"ItemTitle", "ItemText"},

                //ListItem的XML文件里面的两个TextView ID
                new int[] {R.id.ItemTitle,R.id.ItemText});
        //添加并且显示
        list.setAdapter(mSchedule);
        */

    }

    private void initView(){

        listViewData = (ListView) findViewById(R.id.lv_scanlist);

        listEPC = new ArrayList<P_EPC>();
       // listViewData.setOnItemClickListener(this);

    }
    /**
     * 盘存线程
     * @author Administrator
     *
     */
    class InventoryThread extends Thread {
        private List<byte[]> epcList;

        @Override
        public void run() {
            super.run();
            while (runFlag) {
                if (startFlag) {
//					reader.stopInventoryMulti()
                    epcList = reader.inventoryRealTime(); //实时盘存
                    if (epcList != null && !epcList.isEmpty()) {
                        //播放提示音
                        //Util.play(1, 0);
                        for (byte[] epc : epcList) {
                            if (epc != null) {
                               // String epcStr = Tools.Bytes2HexString(epc, epc.length);

                                String _tid=UhfClass.ReadTid(epc);
                                if(_tid!="")
                                {

                                    addToList(listEPC, _tid);
                                }
                                //addToList(listEPC, epcStr);
                            }
                        }
                    }
                    epcList = null;
                    try {
                        Thread.sleep(40);
                    } catch (InterruptedException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                }
            }
        }
    }

    //将读取的EPC添加到LISTVIEW
    private void addToList(final List<P_EPC> list, final String epc){
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                if (fullFlag) {
                    return;
                }
                //第一次读入数据
                if(list.isEmpty()){
                    P_EPC epcTag = new P_EPC();
                    epcTag.setEpc(epc);
                    epcTag.setCount(1);
                    list.add(epcTag);
                }else{
                    for(int i = 0; i < list.size(); i++){
                        P_EPC mEPC = list.get(i);
                        //list中有此EPC
                        if(epc.equals(mEPC.getEpc())){
                            mEPC.setCount(mEPC.getCount() + 1);
                            list.set(i, mEPC);
                            break;
                        }else if(i == (list.size() - 1)){
                            //list中没有此epc
                            P_EPC newEPC = new P_EPC();
                            newEPC.setEpc(epc);
                            newEPC.setCount(1);
                            list.add(newEPC);
                        }
                    }
                }

                _pb.setProgress(list.size());
              //  Log.e("Scan",""+list.size());
                if(list.size()>=_count)
                {
                    fullFlag=true;
                    Log.e("Scan","扫描已满");
                }
                //将数据添加到ListView
                listMap = new ArrayList<Map<String,Object>>();
               // int idcount = 1;
                for(P_EPC epcdata:list){
                    Map<String, Object> map = new HashMap<String, Object>();
                   // map.put("ID", idcount);
                    map.put("ItemTitle", epcdata.getEpc());
                    //map.put("ItemText", "扫描次数:"+epcdata.getCount());
                   // idcount++;
                    listMap.add(map);
                }
                listViewData.setAdapter(new SimpleAdapter(ScanActivity.this,
                        listMap, R.layout.listitem_scan,
                        new String[]{"ItemTitle"},//, "ItemText"
                        new int[]{R.id.ItemTitle}));//, R.id.ItemText
            }
        });
    }
    /**
     * 清空listview
     */
    private void clearData(){
        listEPC.removeAll(listEPC);
        listViewData.setAdapter(null);
        fullFlag=false;
        _pb.setProgress(0);
    }

    public void Scan_onClick(View v) {
        switch (v.getId()) {
            case R.id.bt_save:
                String[] array=new String[listEPC.size()];
                for(int i=0;i<listEPC.size();i++){
                    array[i]=listEPC.get(i).getEpc();
                }



                Intent intent = new Intent();
                intent.putExtra("item_id", _id);
                intent.putExtra("item_list",array);
               // Log.e("Scan_R",array.toString());
                /*
                 * 调用setResult方法表示我将Intent对象返回给之前的那个Activity，这样就可以在onActivityResult方法中得到Intent对象，
                 */
                setResult(1001, intent);
                //    结束当前这个Activity对象的生命
                finish();
                break;
            case R.id.bt_clear:
                clearData();
                break;
        }
    }


    private void _run()
    {
        byte[] versionBytes = reader.getFirmware();
        if(versionBytes != null){
//				reader.setWorkArea(3);//设置成欧标
           // Util.play(1, 0);
          //  String version = new String(versionBytes);
//				textVersion.setText(new String(versionBytes));
          //  setButtonClickable(buttonConnect, false);
          //  setButtonClickable(buttonStart, true);
        }
       // if (readerDevice != null) {
       //     readerDevice.powerOn();
       // }
        /**/
        try {
            FileWriter localFileWriterOn = new FileWriter(new File(
                    "/proc/gpiocontrol/set_id"));
            localFileWriterOn.write("1");
            localFileWriterOn.close();
        } catch (Exception e) {
            Log.e("UHF_1",e.toString());
            e.printStackTrace();

        }
        startFlag=true;
    }

    private void _stop()
    {
        try {
            FileWriter localFileWriterOff = new FileWriter(new File(
                    "/proc/gpiocontrol/set_id"));
            localFileWriterOff.write("0");
            localFileWriterOff.close();
        } catch (Exception e) {
            Log.e("UHF_2",e.toString());
            e.printStackTrace();
        }
    }

    @Override
    protected void onPause() {
        startFlag = false;
        super.onPause();
    }
    @Override
    protected void onDestroy() {
        Log.e("Scan","销毁");
        _stop();
        runFlag = false;
        if(reader != null){
            reader.close();
        }
        if (readerDevice != null) {
            readerDevice.powerOff();
        }
        super.onDestroy();
    }


}
